package com.bolt.report.engine.fill;

import com.bolt.common.collection.IteratorUtil;
import com.bolt.convention.data.Record;
import com.googlecode.aviator.AviatorEvaluator;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class FillReturnValue {

    private List<Record> rawData;

    private Record record;

    private Iterator<Record> iterator;

    private boolean list;

    private boolean page;


    public FillReturnValue() {
        rawData = new ArrayList<>();
        record = new Record();
    }


    public void put(Record record) {
        rawData.add(record);
    }

    public void put(String fieldName, Object value) {
        Record record = new Record();
        record.put(fieldName, value);
        rawData.add(record);
    }

    public void reStart() {
        this.iterator = this.rawData.iterator();
    }

    public boolean next() {

        boolean hasNext = false;
        if (this.iterator != null) {
            hasNext = this.iterator.hasNext();
            if (hasNext) {
                this.record = this.iterator.next();
            }
        }
        return hasNext;
    }

    public boolean next(int start) {
        return next(start, rawData.size());
    }

    public boolean next(int start, int end) {
        boolean hasNext = end >= start;
        if (hasNext) {
            this.record = rawData.get(start);
        }
        return hasNext;
    }

    public List<Record> getRawData() {
        return rawData;
    }

    public Record getRawData(int index) {
        int size = rawData.size();
        if (index >= size) {
            return rawData.get(size - 1);
        } else {
            return rawData.get(index);
        }
    }

    public int getDataSize() {
        if (IteratorUtil.isEmpty(rawData)) {
            return 0;
        } else {
            return rawData.size() - 1;
        }
    }

    public Object getValue(String expression) {
        Object value = null;
        try {
            value = AviatorEvaluator.execute(expression, record);
        } catch (Exception ex) {
            return record;
        }
        return value;
    }

    public Record getRecord() {
        return record;
    }

    public boolean isList() {
        return list;
    }

    public void setList(boolean list) {
        if (this.rawData.size() == 1) {
            this.list = false;
        } else {
            this.list = list;
        }
    }

    public boolean isPage() {
        return page;
    }

    public void setPage(boolean page) {
        this.page = page;
    }
}